package HJwt

import (
	"log"
	"os"
	"strings"
	"time"
)

type Options func(config2 *config)

// WithSig 设置签名
func WithSig(sig string) Options {
	return func(cfg *config) {
		if sig != "" {
			sig = strings.ToUpper(sig)
		}
		cfg.sig = sig
	}
}

func WithKey(k string) Options {
	return func(cfg *config) {
		cfg.key = []byte(k)
	}
}

func WithPriKeyPath(p string) Options {
	return func(cfg *config) {
		key, done := readKey(p)
		if done {
			return
		}
		cfg.priKey = key
		cfg.priKeyPath = p
	}
}

func readKey(p string) ([]byte, bool) {
	if p == "" {
		return nil, true
	}
	key, err := os.ReadFile(p)
	if err != nil {
		log.Printf("读取秘钥失败： %s\n", err.Error())
		return nil, true
	}
	return key, false
}

func WithPubKeyPath(p string) Options {
	return func(cfg *config) {
		key, done := readKey(p)
		if done {
			return
		}
		cfg.pubKey = key
		cfg.pubKeyPath = p
	}
}

func WithExpire(t time.Duration) Options {
	return func(cfg *config) {
		if t < 0 {
			t = 0 - t
		}
		cfg.expiresAt = t
	}
}

func WithMaxRefresh(t time.Duration) Options {
	return func(cfg *config) {
		if t < 0 {
			t = 0 - t
		}
		cfg.maxRefresh = t
	}
}

func WithNbf(t time.Duration) Options {
	return func(cfg *config) {
		if t < 0 {
			t = 0 - t
		}
		cfg.notBefore = t
	}
}

func WithIssuedAt(t time.Duration) Options {
	return func(cfg *config) {
		if t < 0 {
			t = 0 - t
		}
		cfg.issuedAt = t
	}
}
